﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Configuration;
using System.Web;
using System.IO;
using stwh_Model;

namespace stwh_Common
{
    /// <summary>
    /// SMTP 配置类
    /// </summary>
    public class SmtpConfig
    {
        private static SmtpConfig _smtpConfig;
        /// <summary>
        /// 获取SMTP配置文件路径
        /// </summary>
        private string ConfigFile
        {
            get
            {
                //从配置文件获取SMTP配置文件路径
                string configPath = ConfigurationManager.AppSettings["SmtpConfigPath"];
                if (string.IsNullOrEmpty(configPath) || configPath.Trim().Length == 0)
                {
                    configPath = HttpContext.Current.Request.MapPath("/Config/website.config");
                }
                else
                {
                    if (!Path.IsPathRooted(configPath))
                        configPath = HttpContext.Current.Request.MapPath(Path.Combine(configPath, "website.config"));
                    else
                        configPath = Path.Combine(configPath, "website.config");
                }
                return configPath;
            }
        }

        /// <summary>
        /// 获取SMTP属性类（加载SMTP配置文件）
        /// </summary>
        public SmtpSetting SmtpSetting
        {
            get
            {
                SmtpSetting smtpSetting = new SmtpSetting();

                XmlDocument doc = new XmlDocument();
                doc.Load(this.ConfigFile);
                XmlNodeList xmllist = doc.GetElementsByTagName("Websites");
                //获取第一个Website
                XmlNode childxml = xmllist[0].ChildNodes[0];

                smtpSetting.Server = childxml.SelectSingleNode("//emailsmtp").InnerText;
                smtpSetting.Port = int.Parse(childxml.SelectSingleNode("//emailport").InnerText);
                smtpSetting.Authentication = true;
                smtpSetting.User = childxml.SelectSingleNode("//emailuser").InnerText;
                smtpSetting.Password = DEncrypt.DESEncrypt.Decrypt(childxml.SelectSingleNode("//emailpwd").InnerText);
                smtpSetting.Sender = childxml.SelectSingleNode("//emailsend").InnerText;
                smtpSetting.SenderName = childxml.SelectSingleNode("//emailname").InnerText;

                return smtpSetting;
            }
        }

        private SmtpConfig()
        {

        }

        /// <summary>
        /// 创建SmtpConfig
        /// </summary>
        /// <returns></returns>
        public static SmtpConfig Create()
        {
            if (_smtpConfig == null)
            {
                _smtpConfig = new SmtpConfig();
            }
            return _smtpConfig;
        }
    }
}
